import { inject, ref, computed, nextTick } from 'vue';
import { VALIDATE_FAILED } from '../cgform.data';
import { pick } from 'lodash-es';

function useTableSync(columns) {
  const tables = inject('tables');
  const fullScreenRef = inject('fullScreenRef');
  const tableRef = ref();
  const loading = ref(false);
  const dataSource = ref([]);
  const tableHeight = computed(() => ({
    normal: (fullScreenRef == null ? void 0 : fullScreenRef.value) ? 430 : 260,
    noToolbar: (fullScreenRef == null ? void 0 : fullScreenRef.value) ? 480 : 320,
  }));
  const columnKeys = computed(() => ['id'].concat(columns.value.map((col) => col.key)));
  const tableProps = computed(() => {
    return {
      scrollY: {
        gt: 15,
      },
      scrollX: {
        gt: 20,
      },
    };
  });
  async function validateData(activeKey) {
    const instance = tableRef.value;
    const errMap = await instance.fullValidateTable();
    if (errMap) {
      throw { code: VALIDATE_FAILED, activeKey };
    }
    const tableData = instance.getTableData().map((data) => pick(data, columnKeys.value));
    const deleteIds = instance.getDeleteData().map((d) => d.id);
    return { tableData, deleteIds };
  }
  async function setDataSource(data, insert = false) {
    if (insert) {
      dataSource.value = [];
      await nextTick();
      await tableRef.value.addOrInsert(data, 0, null, { setActive: false });
      await nextTick();
      tableRef.value.recalcDisableRows();
    } else {
      dataSource.value = data;
    }
  }
  function syncTable(dbTable) {
    const targetTable = tableRef.value;
    const sourceTable = dbTable.value.tableRef;
    const removeIds = dbTable.value.getRemoveIds();
    const sourceData = sourceTable.getXTable().internalData.tableFullData;
    const targetData = targetTable.getXTable().internalData.tableFullData;
    sourceData.forEach((sourceValue) => {
      let flag = false;
      targetData.forEach((targetValue) => {
        if (sourceValue.id === targetValue.id) {
          const dbFieldName = targetValue['dbFieldName'];
          const dbFieldTxt = targetValue['dbFieldTxt'];
          if (sourceValue.dbFieldName !== dbFieldName || sourceValue.dbFieldTxt !== dbFieldTxt) {
            targetTable.setValues([
              {
                rowKey: targetValue.id,
                values: {
                  dbFieldName: sourceValue.dbFieldName,
                  dbFieldTxt: sourceValue.dbFieldTxt,
                },
              },
            ]);
          }
          flag = true;
        } else {
          removeIds.forEach((deletedId) => {
            if (deletedId === targetValue.id) {
              targetTable.removeRowsById(deletedId);
              flag = true;
            }
          });
        }
      });
      if (!flag) {
        const record = Object.assign({}, sourceValue);
        columns.value.forEach((column) => {
          if (column.key !== 'dbFieldName' && column.key !== 'dbFieldTxt') {
            record[column.key] = column.defaultValue;
          }
        });
        targetTable.addRows(record);
      }
    });
    return nextTick();
  }
  return { tables, tableRef, loading, dataSource, columnKeys, tableHeight, tableProps, syncTable, validateData, setDataSource };
}
export { useTableSync };
